import 'package:cached_network_image/cached_network_image.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sports_new/controller/my/my_system_msg_logic.dart';
import 'package:sports_new/entity/my/my_interact_entity.dart';
import 'package:sports_new/entity/my/my_system_msg_entity.dart';
import 'package:sports_new/resources/colours.dart';
import 'package:sports_new/resources/styles.dart';
import 'package:sports_new/utils/utils.dart';
import 'package:sports_new/utils/widget_utils.dart';
import 'package:sports_new/widgets/loading/no_data_widget.dart';

import '../../widgets/base/qkd_text.dart';

class MySystemMsgPage extends StatefulWidget {
  const MySystemMsgPage({super.key});

  @override
  State<MySystemMsgPage> createState() => _MySystemMsgPageState();
}

class _MySystemMsgPageState extends State<MySystemMsgPage> {
  final logic = Get.put(MySystemMsgLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MySystemMsgLogic>(
      initState: (state) => Utils.onEvent('znx',params: {'znx':1}),
      builder: (_) {
        return Scaffold(
          appBar: Styles.appBar(
            title: Styles.tabbar(
              fontSize: 16,
              controller: logic.tabC,
              tabs: [
                QkdText("系统通知")
                    .marginSymmetric(horizontal: 4)
                    .badge(logic.getUnreadNum(logic.sysCount)),
                QkdText("互动")
                  .marginSymmetric(horizontal: 4)
                  .badge(logic.getUnreadNum(logic.interactCount))
              ],
              onTap: (value){
                Utils.onEvent('znx',params: {'znx':value+1});
              }
            ).sized(width: 180, height: 44),
            actions: [
              Image.asset(
                width: 24,Utils.getImgPath("msg_clear_all.png")
              ).paddingOnly(right: 16).tap(logic.clearMsg)
            ]
          ),
          backgroundColor: Colours.scaffoldBg,
          body: ExtendedTabBarView(
            controller: logic.tabC,
            children: [
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                child: _msgContainer(),
              ),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 10, vertical: 10),
                child: _interContainer(),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _msgContainer() {
    return EasyRefresh(
      onLoad: logic.msgEnd
          ? null
          : () async {
              await logic.getMsgs();
            },
      child: logic.msgs.isEmpty
          ? const NoDataWidget(tip: "暂无系统通知")
          : ListView.builder(
              itemCount: logic.msgs.length,
              itemBuilder: (context, index) {
                final msg = logic.msgs[index];
                return haveRead(
                    msg.read ?? 0, systemCell(msg).marginOnly(bottom: 8));
              }),
    );
  }

  Widget _interContainer() {
    return EasyRefresh(
      onLoad: logic.interEnd
          ? null
          : () async {
              await logic.getInteracts();
            },
      child: logic.interacts.isEmpty
          ? const NoDataWidget(tip: "暂无互动消息")
          : ListView.builder(
              itemCount: logic.interacts.length,
              itemBuilder: (context, index) {
                final inter = logic.interacts[index];
                return haveRead(
                    inter.read ?? 0, interectCell(inter).marginOnly(bottom: 8));
              },
            ),
    );
  }

  Widget haveRead(int r, Widget child) {
    return Stack(
      children: [
        child,
        if (r == 0)
          Positioned(
              top: 8,
              right: 8,
              child: Container(
                width: 6,
                height: 6,
                decoration: const BoxDecoration(
                    shape: BoxShape.circle, color: Colours.main),
              ))
      ],
    );
  }

  Widget systemCell(MySystemMsgEntity e) {
    return GestureDetector(
      onTap: () {
        Utils.doJump(e.url ?? "");
        logic.readMsg(e);
      },
      child: Styles.card(
        width: double.infinity,
        padding: EdgeInsets.symmetric(horizontal: 12, vertical: 12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            QkdText(
              e.title ?? "",
              maxLines: 1,
              fontSize: 16,
              fontWeight: FontWeight.w600,
            ),
            const SizedBox(
              height: 8,
            ),
            QkdText(e.content ?? "",
              fontSize: 15, color: Colours.grey99
            ),
            const SizedBox(
              height: 8,
            ),
            QkdText(
              e.publishTime ?? "",
              fontSize: 12, color: Colours.grey99,
            )
          ],
        ),
      ),
    );
  }

  Widget interectCell(MyInteractEntity e) {
    return GestureDetector(
      onTap: () {
        logic.readInteract(e);
        Utils.doJump(e.href ?? "");
      },
      child: Styles.card(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
                width: 40,
                height: 40,
                clipBehavior: Clip.hardEdge,
                decoration: const BoxDecoration(shape: BoxShape.circle),
                child: CachedNetworkImage(
                    fit: BoxFit.cover,
                    imageUrl: e.eventUserLogo ?? "",
                    errorWidget: (context, url, error) =>
                        Styles.placeholderIcon(),
                    placeholder: (context, url) =>
                        Styles.placeholderIcon())).marginOnly(right: 8),
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: [
                  Text.rich(TextSpan(style: TextStyle(fontSize: 15), children: [
                    TextSpan(
                        text: e.eventUserName ?? "",
                        style: TextStyle(
                            color: Colours.text, fontWeight: FontWeight.w600)),
                    TextSpan(
                        text: " ${e.typeContent}",
                        style: TextStyle(color: Colours.grey66)),
                  ])),
                  if ((e.eventContent ?? "").trim().isNotEmpty)
                    QkdText(
                      e.eventContent ?? "",
                      maxLines: 2,
                    ).marginSymmetric(vertical: 4),
                  QkdText(
                    e.eventTime ?? "",
                    color: Colours.grey99, fontSize: 12
                  )
                ],
              ).marginSymmetric(horizontal: 5),
            ),
            Container(
              clipBehavior: Clip.hardEdge,
              width: 46,
              height: 46,
              padding: const EdgeInsets.all(4),
              decoration: BoxDecoration(
                  color: Colours.greyF5F5F5,
                  borderRadius: BorderRadius.circular(2)),
              child: QkdText(e.originContent ?? "",
                fontSize: 10, color: Colours.grey99, height: 1.3,
                maxLines: 3
              ),
            )
          ],
        ),
      ),
    );
  }
}
